package com.skeryl.sqlite.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.skeryl.sqlite.dao.ChapterDAO;
import com.skeryl.sqlite.model.Chapter;

public class MainActivity extends ListActivity implements OnScrollListener
{
	/**
	 * 是否完成初始化标志
	 */
	private static boolean isInit = false;
	private static String DB_PATH = "/data/data/com.skeryl.sqlite.activity/databases/";
	private static final String DB_NAME = "data.db";
	private static final String TAG = "debug";
	private long COUNT;
	private ListView listview;
	private List<Map<String, Object>> op_data;
	private ChapterDAO chapterDAO;
	private int lastItem, firstItem;
	private SimpleAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		listview = this.getListView();// 取得定义的listview

		init(getApplicationContext());// 初始化数据库

		listview.setCacheColorHint(Color.TRANSPARENT);
		
		chapterDAO = new ChapterDAO();// 取得数据库链接

		op_data = new ArrayList<Map<String, Object>>();

		COUNT = chapterDAO.getCount();

		chapterDAO.closeAddGet();// 关闭并取得数据库链接

		op_data = getData(chapterDAO, 0, (int) COUNT);

		chapterDAO.close();// 关闭数据库链接

		adapter = new SimpleAdapter(this, op_data, R.layout.main, new String[]
		{ "sid", "title" }, new int[]
		{ R.id.title, R.id.content });

		listview.setAdapter(adapter);
		listview.setOnScrollListener(this);

	}

	/*
	 * 单击事件
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	protected void onListItemClick(ListView l, View v, int position, long id)
	{

		super.onListItemClick(l, v, position, id);

		// Toast.makeText(getApplicationContext(), "点击第" + position + "个项目",
		// Toast.LENGTH_SHORT).show();
		Toast.makeText(getApplicationContext(), "进入" + op_data.get(position).get("title") + "。。。", Toast.LENGTH_SHORT).show();

		chapterDAO.closeAddGet();

		Intent it = new Intent(MainActivity.this, ChapterActivity.class);
		Bundle bundle = new Bundle();

		Chapter chapter = chapterDAO.find(op_data.get(position).get("sid").toString());
		bundle.putString("content", chapter.getContent());
		bundle.putString("sid", op_data.get(position).get("sid").toString());
		it.putExtras(bundle);
		startActivity(it);

	}

	/**
	 * firstVisibleItem：当前能看见的第一个列表项ID（从0开始）
	 * visibleItemCount：当前能看见的列表项总数（小半个也算，部分显示的都算） totalItemCount：列表项共数
	 * onScroll是在“滑动”执行过之后才触发
	 */

	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	{
		lastItem = listview.getLastVisiblePosition();
		firstItem = listview.getFirstVisiblePosition();
	}

	public void onScrollStateChanged(AbsListView paramAbsListView, int scrollState)
	{

		switch (scrollState)
		{

		case OnScrollListener.SCROLL_STATE_IDLE:// 当不滚动时

			if (lastItem == listview.getCount() - 1)// 判断滚动到底部
													// ，listview的index从0开始
			{
				List<Map<String, Object>> sub_data = getData(chapterDAO, firstItem, lastItem);

				if (sub_data.size() < 1)// 取不到数据时 注意： listview的index从0开始
				{
					Toast.makeText(getApplicationContext(), "亲！到底了哦。。。", Toast.LENGTH_SHORT).show();
				} else
				{
					op_data.addAll(sub_data);
					adapter.notifyDataSetChanged();// 刷新list
				}

			}
			// 判断滚动到顶部
			if (listview.getFirstVisiblePosition() == 0)
			{

			}

			break;
		}

	}

	/*
	 * 从数据库中取出数据
	 */
	public List<Map<String, Object>> getData(ChapterDAO chapterDAO, int start, int end)

	{

		chapterDAO.closeAddGet();

		List<Chapter> chapters;
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

		if (start == 0 && end >= 40)
		{
			System.out.println("第一页！ ： " + start + " " + end);
			chapters = chapterDAO.getScrollData(0, 40);// 如果是第一页，并且数据库中的数据大于40条，直接返回40条数据
		} else if (start == 0 && end < 40)
		{
			System.out.println("第一页！ ： " + start + " " + end);

			chapters = chapterDAO.getScrollData(0, end);// 如果是第一页，数据库中的数据小于40条，直接返回所有数据
		} else if (end + end - start > COUNT)
		{// 如果剩余数据的数目小于一页显示的数目
			chapters = chapterDAO.getScrollData(end, (int) (COUNT - end));

		} else
		{
			System.out.println("中间页！ ： " + start + " " + end);
			chapters = chapterDAO.getScrollData(end, end - start);

		}

		for (int i = 0; i < chapters.size(); i++)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sid", chapters.get(i).getSid());
			map.put("title", chapters.get(i).getTitle());

			data.add(map);
		}
		System.out.println("返回数据长度 ： " + data.size());
		chapterDAO.close();

		return data;

	}

	/**
	 * 初始化数据库
	 * 
	 * @param context
	 */
	synchronized public static void init(Context context)
	{
		if (isInit)
			return;
		// 输出路径
		String outFileName = DB_PATH + DB_NAME;

		// 检测是否已经创建
		File dir = new File(outFileName);
		if (dir.exists())
			return;

		// 检测/创建数据库的文件夹
		dir = new File(DB_PATH);

		if (!dir.exists())
			dir.mkdir();

		InputStream input = null;
		OutputStream output = null;
		// 从资源中读取数据库流
		input = context.getResources().openRawResource(R.raw.data);

		try
		{
			output = new FileOutputStream(outFileName);

			// 拷贝到输出流
			byte[] buffer = new byte[2048];
			int length;
			while ((length = input.read(buffer)) > 0)
			{
				output.write(buffer, 0, length);
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			// 关闭输出流
			try
			{
				output.flush();
				output.close();
			} catch (IOException e)
			{
			}
			// 关闭输入流
			try
			{
				input.close();
			} catch (IOException e)
			{
			}
		}
		isInit = true;
	}
}